package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"math"
	"path/filepath"
	"strconv"
	"strings"
	"video/models"
	"video/re"
)

type VideoControllers struct {
	beego.Controller
}

type Json struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *VideoControllers) Add() {
	// 从请求中获取数据
	title := c.GetString("title")
	author := c.GetString("author")
	cate := c.GetString("cate")

	// 校验作者格式
	if !re.IsValidChinese(author) {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "作者格式不正确，必须为2-4为中文",
			Data: nil,
		}
		c.ServeJSON()
		return // 需要在这里返回，以防继续执行
	}

	// 创建一个新的 Video 实例
	video := models.Video{
		Title:  title,
		Author: author,
		Cate:   cate,
	}

	// 添加视频到数据库
	err := models.Add(&video)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return // 如果添加失败，需要返回
	}

	key := "video-" + strconv.Itoa(int(video.Id))
	jsonByte, jsonErr := json.Marshal(video)
	if jsonErr != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "JSON 编码失败",
			Data: nil,
		}
		c.ServeJSON()
		return // 如果 JSON 编码失败，需要返回
	}

	// 添加到 Redis 缓存
	models.Rdb.Set(key, string(jsonByte), 0)

	c.Data["json"] = Json{
		Code: 200,
		Msg:  "添加成功",
		Data: jsonByte,
	}
	c.ServeJSON()
}

func (c *VideoControllers) Del() {
	id, _ := c.GetInt("id")
	err := models.Del(id)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *VideoControllers) List() {
	list, err := models.List()
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功",
			Data: list,
		}
		c.ServeJSON()
	}
}

func (c *VideoControllers) Page() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	key := "page" + "-" + strconv.Itoa(page) + "-" + strconv.Itoa(pageSize)
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		videos, count, err := models.Page(page, pageSize)
		if err != nil {
			c.Data["json"] = Json{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["videos"] = videos
			pageData["count"] = count
			jsonByte, _ := json.Marshal(pageData)
			models.Rdb.Set(key, string(jsonByte), 0)
			c.Data["json"] = Json{
				Code: 200,
				Msg:  "分页成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "分页成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}
func (c *VideoControllers) Page1() {
	//1.总数
	var count int64
	err := models.DB.Model(models.Video{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	//2.每条页数
	size, _ := c.GetInt("size", 5)
	//3.页数
	sum := int(math.Ceil(float64(count) / float64(size)))
	//4.当前页
	page, _ := c.GetInt("p", 1)
	//5.偏移量
	offset := (page - 1) * size
	//6.查询
	var video []models.Video
	err = models.DB.Offset(offset).Limit(size).Find(&video).Error
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["sum"] = sum
		pageData["video"] = video
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *VideoControllers) Show() {

	id, _ := c.GetInt("id")
	key := "video-" + strconv.Itoa(id)
	var video models.Video
	val, err := models.Rdb.Get(key).Result() //获取缓存
	if err != nil {
		err = models.DB.Model(&video).Where("id=?", id).First(&video).Error
		if err != nil {
			c.Data["json"] = Json{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		jsonByte, _ := json.Marshal(video)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功-mysql",
			Data: video,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &video)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: video,
		}
		c.ServeJSON()
	}
	/*id, _ := c.GetInt("id")
	var video *models.Video
	err := models.DB.Model(&video).Where("id=?", id).First(&video).Error
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功",
			Data: video,
		}
		c.ServeJSON()
	}*/
}

func (c *VideoControllers) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close() //延迟关闭文件

	//文件大小不能超过 字节
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件过大不能超过2M",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	//文件格式验证 .png .jpg .jpeg
	//strings.ToLower 转小写
	//filepath.Ext 用户获取文件的扩展名
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMap := map[string]bool{
		".png":  true,
		".jpeg": true,
		".jpg":  true,
	}
	if !suffixMap[suffix] {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件格式仅支持png,jpeg,jpg",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgSrc := "http://localhost:8080/" + path
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "文件上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}
}

func (c *VideoControllers) Modification() {
	title := c.GetString("title")
	author := c.GetString("author")
	cate := c.GetString("cate")
	id, _ := c.GetInt("id")
	video := models.Video{
		Model:  gorm.Model{ID: uint(id)},
		Title:  title,
		Author: author,
		Cate:   cate,
	}
	err := models.DB.Updates(&video).Error
	if err != nil {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		key := "video-" + strconv.Itoa(id)
		jsonByte, _ := json.Marshal(&video)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
